﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Web;

public partial class Common_Code : System.Web.UI.Page 
{
    private void Page_Load(object sender, EventArgs e)
    {
        string vNum = HZ.Fun2.GetRandomStr(4);
        //保存验证码
        CurrentAccount.SetValidateCode(vNum);
        this.ValidateCode(vNum);
    }

    /// <summary>
    /// 生成随机数
    /// </summary>
    /// <param name="VcodeNum"></param>
    /// <returns></returns>
    public string RndNum(int VcodeNum)
    {
        string[] strArray = "0,1,2,3,4,5,6,7,8,9".Split(new char[] { ',' });
        string str2 = "";
        int num = -1;
        Random random = new Random();
        for (int i = 1; i < (VcodeNum + 1); i++)
        {
            if (num != -1)
            {
                random = new Random((i * num) * ((int)DateTime.Now.Ticks));
            }
            int index = random.Next(9);
            if ((num != -1) && (num == index))
            {
                return this.RndNum(VcodeNum);
            }
            num = index;
            str2 = str2 + strArray[index];
        }
        return str2;
    }

    /// <summary>
    /// 输出验证码图片
    /// </summary>
    /// <param name="VNum"></param>
    private void ValidateCode(string VNum)
    {
        int width = (int)(VNum.Length * 11.5);
        Bitmap image = new Bitmap(width, 0x14);
        Graphics graphics = Graphics.FromImage(image);

        //生成随机生成器
        Random random = new Random();

        //清空图片背景色
        graphics.Clear(Color.WhiteSmoke);

        //画图片的背景噪音线
        for (int i = 0; i < 5; i++)
        {
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);

            graphics.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        }

        graphics.DrawString(VNum, new Font("宋体", 14f, FontStyle.Bold), new SolidBrush(Color.Red), (float)0f, (float)0f);
        MemoryStream stream = new MemoryStream();
        image.Save(stream, ImageFormat.Png);
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ContentType = "image/png";
        HttpContext.Current.Response.BinaryWrite(stream.ToArray());
        graphics.Dispose();
        image.Dispose();
        HttpContext.Current.Response.End();
    }
}
